﻿using System;

namespace Utilities
{
    /// <summary>
    /// Generic task
    /// </summary>
    public abstract class TaskBase
    {
        #region Properties

        /// <summary>
        /// The unique name of the task in the jbo
        /// </summary>
        public string Id { get; set; }

        public TaskBase OnSuccess { get; set; }

        public TaskBase OnError { get; set; }
        
        #endregion

        #region Methods

        public void Run(Job job, TaskData input)
        {
            // Log task started

            try
            {

                TaskData data = Execute(job, input);

                if (OnSuccess != null) // There are more tasks to be executed
                {
                    OnSuccess.Run(job, data);
                }
                else // There are no more tasks to be executed, pass the result to the job
                {
                    job.Result = data;
                }
            }
            catch (Exception exception)
            {

                TaskData error = new TaskData
                {
                    Error = exception
                };

                if (OnError != null) // Let the task handle the error
                {
                    OnError.Run(job, error);
                }
                else // Let the job handle the error
                {
                    if (job.OnError != null)
                    {
                        job.OnError.Run(job, error);
                    }
                    else
                    {
                        // Log task error
                        throw;
                    }
                }
            }

            // Log task ended
        }
        
        #endregion

        #region Overridables

        protected abstract TaskData Execute(Job job, TaskData input); 

        #endregion
    }
}
